package jnpf.wx;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;

public class SignatureUtil {

    private static final String VENDOR_SN = "91802673";
    private static final String VENDOR_KEY = "8c8730225503ca57e64d594104f420a7";
    // 终端激活接口地址
    private static final String ACTIVATE_API_URL = "https://vsi-api.shouqianba.com/terminal/activate";

    /**
     * 生成API请求的签名
     * @param requestBody 请求的JSON字符串
     * @return 包含签名序列号和签名值的Authorization头部值
     */
    public static String generateAuthorizationHeader(String requestBody) {
        String sign = generateSignature(requestBody, VENDOR_KEY);
        return VENDOR_SN + " " + sign;
    }

    /**
     * 生成签名值
     * @param requestBody 请求的JSON字符串
     * @param secretKey 商户密钥
     * @return MD5签名值(32位大写)
     */
    public static String generateSignature(String requestBody, String secretKey) {
        try {
            // 拼接body和key（按现有规则：请求体JSON + 密钥）
            String content = requestBody + secretKey;
            // 获取MD5摘要算法的 MessageDigest 对象
            MessageDigest md = MessageDigest.getInstance("MD5");
            // 使用指定的字节更新摘要
            md.update(content.getBytes("UTF-8"));
            // 获得密文
            byte[] digest = md.digest();
            // 把密文转换成十六进制的字符串形式
            StringBuilder hexString = new StringBuilder();
            for (byte b : digest) {
                String hex = Integer.toHexString(0xFF & b);
                if (hex.length() == 1) {
                    hexString.append('0');
                }
                hexString.append(hex);
            }
            return hexString.toString().toUpperCase();
        } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
            throw new RuntimeException("生成签名失败", e);
        }
    }

    /**
     * 生成签名序列号
     * 实际项目中建议使用更安全的随机数生成方式，如UUID或时间戳+随机数
     */
    private static String generateSignatureSerialNumber() {
        return UUID.randomUUID().toString().replace("-", "");
    }

    // -------------------------- 新增：终端激活接口调用方法 --------------------------

    /**
     * 调用终端激活接口
     * @param appId 应用ID
     * @param code 激活码内容
     * @param clientSn 第三方终端号（可选）
     * @param name 终端名（可选）
     * @param osInfo 系统信息（可选）
     * @param sdkVersion SDK版本（可选）
     * @return 接口响应JSON字符串
     */
    public static String activateTerminal(String appId, String code, String clientSn, String name, String osInfo, String sdkVersion) {
        // 1. 构建请求参数
        JSONObject requestData = new JSONObject();
        requestData.put("app_id", appId); // 必传
        requestData.put("code", code); // 必传
        requestData.put("device_id", "渝港-WX"); // 固定device_id

        // 可选参数（非空才添加）
        if (clientSn != null && !clientSn.isEmpty()) {
            requestData.put("client_sn", clientSn);
        }
        if (name != null && !name.isEmpty()) {
            requestData.put("name", name);
        }
        if (osInfo != null && !osInfo.isEmpty()) {
            requestData.put("os_info", osInfo);
        }
        if (sdkVersion != null && !sdkVersion.isEmpty()) {
            requestData.put("sdk_version", sdkVersion);
        }

        // 2. 生成请求体JSON字符串
        String requestBody = requestData.toString();
        System.out.println("请求体：" + requestBody);

        // 3. 生成Authorization头（复用现有签名方法）
        String authorization = generateAuthorizationHeader(requestBody);
        System.out.println("Authorization：" + authorization);

        // 4. 发送POST请求并返回响应
        return sendActivateRequest(requestBody, authorization);
    }

    /**
     * 发送终端激活请求
     */
    private static String sendActivateRequest(String requestBody, String authorization) {
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            // 创建POST请求
            HttpPost httpPost = new HttpPost(ACTIVATE_API_URL);

            // 设置请求头
            httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");
            httpPost.setHeader("Authorization", authorization); // 传入生成的签名头

            // 设置请求体
            StringEntity entity = new StringEntity(requestBody, StandardCharsets.UTF_8);
            httpPost.setEntity(entity);

            // 执行请求并获取响应
            try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
                int statusCode = response.getStatusLine().getStatusCode();
                System.out.println("响应状态码：" + statusCode);

                HttpEntity responseEntity = response.getEntity();
                if (responseEntity != null) {
                    String responseBody = EntityUtils.toString(responseEntity, StandardCharsets.UTF_8);
                    System.out.println("响应内容：" + responseBody);
                    return responseBody;
                }
                return "响应内容为空";
            }
        } catch (Exception e) {
            throw new RuntimeException("终端激活请求失败", e);
        }
    }

    // 示例用法
    public static void main(String[] args) {
        // 调用终端激活接口（替换为实际参数）
        String appId = "2025070300009367"; // 必传
        String code = "10528136"; // 必传
        String clientSn = ""; // 可选
        String name = ""; // 可选
        String osInfo = ""; // 可选
        String sdkVersion = "";



        try {
            String result = activateTerminal(appId, code, clientSn, name, osInfo, sdkVersion);
            System.out.println("激活结果：" + result);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}